package com.krdz.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.krdz.bean.UserBean;
import com.krdz.dao.UserDao;
import com.krdz.service.UserService;
/**
 * 用户管理业务层实现
 * @author dinghao
 *
 * @date  2018年11月15日
 */
@Service("UserServiceImpl")
public class UserServiceImpl implements UserService{
	
	@Resource
	private UserDao userDao;
	
	private String rootPath;
	//查询用户基本信息
	@Override
	public List<UserBean> findUserInfo() {
		
		return userDao.findUserInfo();
	}
	//根据ID查询用户信息
	@Override
	public List<UserBean> findUserById(Integer id) {
	
		return userDao.findUserById(id);
	}
	//新增用户信息
	@Override
	public boolean add(UserBean bean) {
		
		return userDao.add(bean).equals(1)?true:false;
	}
	//修改用户信息
	@Override
	public boolean updateUser(UserBean user) {
		
		return userDao.updateUser(user).equals(1)?true:false;
	}
	//删除用户
	@Override
	public boolean deleteUser(Integer id) {
		
		return userDao.deleteUser(id).equals(1)?true:false;
	}
	//头像上传业务实现
	@Override
	public Map<String, Object> uploadTest(MultipartFile file, HttpServletRequest request) {
		Map<String,Object> result=new HashMap<String,Object>();
		
		this.rootPath = "D:/QR_File/";//上传文件的跟路径
		final String uploadPath = rootPath + new SimpleDateFormat("yyyy/MM/dd").format(new Date());//上传的组合路径
		final String fileName = file.getOriginalFilename(); //上传的文件名		
		File saveFile = new File(uploadPath, fileName);
		
		if(!saveFile.exists())
			saveFile.mkdirs();//目录不存在，递归创建
		String[] suffixs={".jpg",".png",".jpeg",".gif",".bmp"};
		if(Arrays.asList(suffixs).contains(getSuffix(saveFile.getName())) == false){//上传文件名检查（白名单机制）true:通过，false：没有通过
			result.put("code", 500);result.put("msg", "上传文件格式不支持");
		}else{
			try {
				file.transferTo(saveFile);//保存文件
				result.put("code", 200);
				result.put("msg", "上传成功");
				result.put("data", new HashMap<String, Object>() {  
					 {  
						 put("src", uploadPath + "/"+ fileName);   
					 }  
				});
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return result;
	}

	/**
	 * 文件后缀
	 * @return
	 */
	public String getSuffix(String name) {
		String suffix = name;
		if(suffix.contains("."))
			suffix = suffix.substring(suffix.lastIndexOf("."));
		else
			suffix = "";
		return suffix;
	}
	
	//查询用户总记录数
	@Override
	public Integer findUserCount() {
		
		return userDao.findUserCount();
	}
}
